package com.example.managemyself.util;

import android.content.Context;
import android.util.Log;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.data.model.User;
import com.example.managemyself.util.OpenWeatherHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * AI数据管理器
 * 为AI提供完整的应用数据访问能力
 * 包括用户数据、任务、日记、身体状态、天气、黄历等所有数据
 */
public class AIDataManager {
    
    private static final String TAG = "AIDataManager";
    private static AIDataManager instance;
    
    private final Context context;
    private final AppDatabase database;
    private final ExecutorService executorService;
    private final UserManager userManager;
    private final WeatherCacheManager weatherCacheManager;
    
    // 数据缓存
    private String cachedUserContext = null;
    private long lastCacheTime = 0;
    private static final long CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存
    
    private AIDataManager(Context context) {
        this.context = context.getApplicationContext();
        this.database = AppDatabase.getInstance(context);
        this.executorService = Executors.newSingleThreadExecutor();
        this.userManager = UserManager.getInstance();
        this.userManager.init(context);
        this.weatherCacheManager = WeatherCacheManager.getInstance(context);
    }
    
    public static synchronized AIDataManager getInstance(Context context) {
        if (instance == null) {
            instance = new AIDataManager(context);
        }
        return instance;
    }
    
    /**
     * 获取完整的用户上下文数据（异步）
     */
    public void getCompleteUserContext(DataCallback callback) {
        // 检查缓存
        if (isCacheValid()) {
            callback.onSuccess(cachedUserContext);
            return;
        }
        
        executorService.execute(() -> {
            try {
                String context = buildCompleteUserContext();
                cachedUserContext = context;
                lastCacheTime = System.currentTimeMillis();
                callback.onSuccess(context);
            } catch (Exception e) {
                Log.e(TAG, "获取用户上下文失败", e);
                callback.onError("获取用户数据失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 构建完整的用户上下文数据
     */
    private String buildCompleteUserContext() throws Exception {
        JSONObject contextData = new JSONObject();
        
        // 1. 基本信息
        contextData.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
        contextData.put("app_name", "ManageMyself");
        contextData.put("data_version", "1.0");
        
        // 2. 用户信息
        JSONObject userInfo = getUserInfo();
        if (userInfo != null) {
            contextData.put("user_info", userInfo);
        }
        
        // 3. 任务数据
        JSONObject tasksData = getTasksData();
        if (tasksData != null) {
            contextData.put("tasks", tasksData);
        }
        
        // 4. 日记数据
        JSONObject diaryData = getDiaryData();
        if (diaryData != null) {
            contextData.put("diary", diaryData);
        }
        
        // 5. 天气数据
        JSONObject weatherData = getWeatherData();
        if (weatherData != null) {
            contextData.put("weather", weatherData);
        }
        
        // 6. 黄历数据
        JSONObject calendarData = getCalendarData();
        if (calendarData != null) {
            contextData.put("calendar", calendarData);
        }
        
        // 7. 身体状态数据
        JSONObject healthData = getHealthData();
        if (healthData != null) {
            contextData.put("health", healthData);
        }
        
        // 8. 应用设置
        JSONObject settingsData = getSettingsData();
        if (settingsData != null) {
            contextData.put("settings", settingsData);
        }
        
        return contextData.toString(2); // 格式化输出
    }
    
    /**
     * 获取用户基本信息
     */
    private JSONObject getUserInfo() {
        try {
            User currentUser = userManager.getCurrentUser();
            if (currentUser == null) {
                return null;
            }
            
            JSONObject userInfo = new JSONObject();
            userInfo.put("user_id", currentUser.getId());
            userInfo.put("username", currentUser.getUsername());
            userInfo.put("email", currentUser.getEmail());
            userInfo.put("role", currentUser.getRole());
            userInfo.put("active", currentUser.isActive());
            userInfo.put("created_date", currentUser.getCreatedDate() != null ? 
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(currentUser.getCreatedDate()) : null);
            userInfo.put("last_login", currentUser.getLastLoginDate() != null ? 
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(currentUser.getLastLoginDate()) : null);
            
            // 扩展个人信息
            userInfo.put("nickname", currentUser.getNickname());
            userInfo.put("phone", currentUser.getPhone());
            userInfo.put("gender", currentUser.getGender());
            userInfo.put("bio", currentUser.getBio());
            userInfo.put("occupation", currentUser.getOccupation());
            userInfo.put("city", currentUser.getCity());
            userInfo.put("hobbies", currentUser.getHobbies());
            
            return userInfo;
        } catch (Exception e) {
            Log.e(TAG, "获取用户信息失败", e);
            return null;
        }
    }
    
    /**
     * 获取任务数据
     */
    private JSONObject getTasksData() {
        try {
            User currentUser = userManager.getCurrentUser();
            if (currentUser == null) {
                return null;
            }
            
            // 使用现有的同步方法
            List<Task> allTasks = database.taskDao().getAllTasksSync();
            List<Task> pendingTasks = database.taskDao().getPendingTasksSync();
            
            // 计算已完成任务数量
            int completedCount = 0;
                for (Task task : allTasks) {
                if (task.isCompleted()) {
                    completedCount++;
                }
            }
            
            JSONObject tasksData = new JSONObject();
            tasksData.put("total_count", allTasks.size());
            tasksData.put("completed_count", completedCount);
            tasksData.put("pending_count", pendingTasks.size());
            
            // 按类型统计
            JSONObject tasksByType = new JSONObject();
            for (Task task : allTasks) {
                String type = task.getType() != null ? task.getType() : "未分类";
                int count = tasksByType.optInt(type, 0);
                tasksByType.put(type, count + 1);
            }
            tasksData.put("tasks_by_type", tasksByType);
            
            // 最近的任务
            JSONArray recentTasks = new JSONArray();
            int recentCount = Math.min(10, allTasks.size());
            for (int i = 0; i < recentCount; i++) {
                Task task = allTasks.get(i);
                JSONObject taskObj = new JSONObject();
                taskObj.put("id", task.getId());
                taskObj.put("title", task.getTitle());
                taskObj.put("description", task.getDescription());
                taskObj.put("type", task.getType());
                taskObj.put("importance", task.getImportance());
                taskObj.put("urgency", task.getUrgencyDisplayText());
                taskObj.put("completed", task.isCompleted());
                taskObj.put("status", task.getStatus());
                taskObj.put("created_date", task.getCreatedDate() != null ? 
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(task.getCreatedDate()) : null);
                taskObj.put("due_date", task.getDueDate() != null ? 
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(task.getDueDate()) : null);
                recentTasks.put(taskObj);
            }
            tasksData.put("recent_tasks", recentTasks);
            
            return tasksData;
        } catch (Exception e) {
            Log.e(TAG, "获取任务数据失败", e);
            return null;
        }
    }
    
    /**
     * 获取日记数据
     */
    private JSONObject getDiaryData() {
        try {
            User currentUser = userManager.getCurrentUser();
            if (currentUser == null) {
                return null;
            }
            
            // 使用现有的同步方法获取最近的日记
            List<DiaryEntry> allEntries = database.diaryEntryDao().getRecentDiariesSync(30); // 获取最近30天的日记
            
            JSONObject diaryData = new JSONObject();
            diaryData.put("total_entries", allEntries.size());
            
            // 最近的日记条目
            JSONArray recentEntries = new JSONArray();
            int recentCount = Math.min(5, allEntries.size());
            for (int i = 0; i < recentCount; i++) {
                DiaryEntry entry = allEntries.get(i);
                JSONObject entryObj = new JSONObject();
                entryObj.put("id", entry.getId());
                entryObj.put("title", entry.getTitle());
                entryObj.put("content", entry.getContent());
                entryObj.put("mood", entry.getMood());
                entryObj.put("weather", entry.getWeather());
                entryObj.put("created_date", entry.getCreatedDate() != null ? 
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(entry.getCreatedDate()) : null);
                recentEntries.put(entryObj);
            }
            diaryData.put("recent_entries", recentEntries);
            
            return diaryData;
        } catch (Exception e) {
            Log.e(TAG, "获取日记数据失败", e);
            return null;
        }
    }
    
    /**
     * 获取天气数据
     */
    private JSONObject getWeatherData() {
        try {
            if (weatherCacheManager == null) {
                return null;
            }
            
            // 获取缓存的天气数据
            OpenWeatherHelper.WeatherInfo cachedWeather = weatherCacheManager.getCachedWeather("汕尾");
            
            JSONObject weatherData = new JSONObject();
            if (cachedWeather != null) {
                weatherData.put("city", cachedWeather.cityName);
                weatherData.put("temperature", cachedWeather.temperature + "°C");
                weatherData.put("weather_text", cachedWeather.weatherText);
                weatherData.put("humidity", cachedWeather.humidity + "%");
                weatherData.put("wind_speed", cachedWeather.windSpeed + " km/h");
                weatherData.put("cached_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
                weatherData.put("cache_remaining_minutes", weatherCacheManager.getCacheRemainingTime());
            } else {
                weatherData.put("status", "无缓存数据");
            }
            
            return weatherData;
        } catch (Exception e) {
            Log.e(TAG, "获取天气数据失败", e);
            return null;
        }
    }
    
    /**
     * 获取黄历数据
     */
    private JSONObject getCalendarData() {
        try {
            // 这里可以集成黄历API数据
            JSONObject calendarData = new JSONObject();
            calendarData.put("date", new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date()));
            calendarData.put("lunar_date", "农历数据待集成");
            calendarData.put("suitable_activities", "宜：待集成");
            calendarData.put("unsuitable_activities", "忌：待集成");
            calendarData.put("note", "黄历功能待完善");
            
            return calendarData;
        } catch (Exception e) {
            Log.e(TAG, "获取黄历数据失败", e);
            return null;
        }
    }
    
    /**
     * 获取身体状态数据
     */
    private JSONObject getHealthData() {
        try {
            JSONObject healthData = new JSONObject();
            
            // 模拟健康数据（实际应用中应从健康数据库获取）
            healthData.put("heart_rate", "72 bpm");
            healthData.put("steps", "8,500 步");
            healthData.put("sleep_hours", "7.5 小时");
            healthData.put("meditation_minutes", "10 分钟");
            healthData.put("last_exercise", "昨天");
            healthData.put("note", "健康数据为模拟数据，华为手环集成待开发");
            
            // 白噪音播放状态
            try {
                WhiteNoisePlayer player = WhiteNoisePlayer.getInstance(context);
                WhiteNoisePlayer.PlaybackStatistics stats = player.getPlaybackStatistics();
                JSONObject whiteNoiseData = new JSONObject();
                whiteNoiseData.put("current_noise", stats.getCurrentNoise());
                whiteNoiseData.put("play_state", stats.getPlayState());
                whiteNoiseData.put("volume", stats.getVolume());
                whiteNoiseData.put("looping", stats.isLooping());
                healthData.put("white_noise_status", whiteNoiseData);
            } catch (Exception e) {
                healthData.put("white_noise_status", "获取失败");
            }
            
            return healthData;
        } catch (Exception e) {
            Log.e(TAG, "获取健康数据失败", e);
            return null;
        }
    }
    
    /**
     * 获取应用设置数据
     */
    private JSONObject getSettingsData() {
        try {
            JSONObject settingsData = new JSONObject();
            
            // 从SharedPreferences获取设置
            android.content.SharedPreferences prefs = context.getSharedPreferences("app_settings", Context.MODE_PRIVATE);
            
            settingsData.put("notifications_enabled", prefs.getBoolean("notifications_enabled", true));
            settingsData.put("dark_mode", prefs.getBoolean("dark_mode", false));
            settingsData.put("auto_sync", prefs.getBoolean("auto_sync", true));
            settingsData.put("backup_enabled", prefs.getBoolean("backup_enabled", false));
            settingsData.put("language", prefs.getString("language", "zh-CN"));
            settingsData.put("theme", prefs.getString("theme", "default"));
            
            return settingsData;
        } catch (Exception e) {
            Log.e(TAG, "获取设置数据失败", e);
            return null;
        }
    }
    
    /**
     * 检查缓存是否有效
     */
    private boolean isCacheValid() {
        return cachedUserContext != null && 
               (System.currentTimeMillis() - lastCacheTime) < CACHE_DURATION;
    }
    
    /**
     * 清除缓存
     */
    public void clearCache() {
        cachedUserContext = null;
        lastCacheTime = 0;
    }
    
    /**
     * 获取特定类型的数据（异步）
     */
    public void getSpecificData(String dataType, DataCallback callback) {
        executorService.execute(() -> {
            try {
                JSONObject result = null;
                
                switch (dataType.toLowerCase()) {
                    case "user":
                        result = getUserInfo();
                        break;
                    case "tasks":
                        result = getTasksData();
                        break;
                    case "diary":
                        result = getDiaryData();
                        break;
                    case "weather":
                        result = getWeatherData();
                        break;
                    case "calendar":
                        result = getCalendarData();
                        break;
                    case "health":
                        result = getHealthData();
                        break;
                    case "settings":
                        result = getSettingsData();
                        break;
                    default:
                        callback.onError("未知的数据类型: " + dataType);
                        return;
                }
                
                if (result != null) {
                    callback.onSuccess(result.toString(2));
                } else {
                    callback.onError("无法获取 " + dataType + " 数据");
            }
            
        } catch (Exception e) {
                Log.e(TAG, "获取特定数据失败: " + dataType, e);
                callback.onError("获取数据失败: " + e.getMessage());
        }
        });
    }
    
    /**
     * 数据回调接口
     */
    public interface DataCallback {
        void onSuccess(String data);
        void onError(String error);
    }
    
    /**
     * 释放资源
     */
    public void release() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
        clearCache();
    }
} 